package readini

import (
	"bufio"
	"os"
	"runtime"
)

//ListenFunc listen ini file
type ListenFunc func(string)

//Listener the interface of listen function
type Listener interface {
	listen(inifile string)
}

func (listenFunc ListenFunc) listen(filename string) {
	listenFunc(filename)
}

//Init initialize
func Init() {
	switch runtime.GOOS {
	case "windows":
		CommentSign = ";"
		LineBreak = "\r\n"
	case "linux":
		CommentSign = "#"
		LineBreak = "\n"
	}
}

// Load load and parse ini file
func Load(filename string) (*Configuration, error) {
	Init()
	file, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	buffer := bufio.NewReader(file)
	var cfg Configuration
	cfg.init()
	err = parse(&cfg, buffer)

	if err != nil {
		return nil, err
	}

	return &cfg, nil
}

//Watch watch and listen ini file
func Watch(filename string, listener Listener) (*Configuration, error) {
	listener.listen(filename)
	conf, err := Load(filename)
	if err != nil {
		return nil, err
	}
	return conf, nil
}
